<template>
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
        <div class="tabs">
            <div class="tabs-title" id="baseInfo">基本信息</div>
            <div style="width: 100%" class="form">
                <el-form
                    :model="formData"
                    :rules="rules"
                    ref="ruleForm"
                    label-width="240px"
                >
                    <el-row>
                        <!-- <el-col :span="12">
                            <el-form-item label="结算编号" prop="billNo">
                                {{ formData.billNo }}
                            </el-form-item>
                        </el-col> -->
                        <el-col :span="12">
                            <el-form-item label="单据机构" prop="orgName">
                                {{ formData.orgName }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="合同类型" prop='contractTypeName'>
                                {{ formData.contractTypeName }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="合同名称" prop='contractName'>
                                {{ formData.contractName }}&nbsp;
                                <span
                                    class="a"
                                    @click="onViewContract"
                                    v-if="formData.contractBillId"
                                    >查看</span
                                >
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item
                                label="结算单位"
                                prop="settlementUnitName"
                            >
                                <div style="display: flex; width: 100%">
                                    <el-input
                                        style="flex: 1; margin: 0 5px 0 0"
                                        placeholder="请选择合同名称"
                                        v-model="formData.settlementUnitName"
                                        readonly
                                        v-if='!isRedSingle'
                                    >
                                        <i
                                            slot="suffix"
                                            class="el-icon-document-copy"
                                            @click="onSelectHetong"
                                        ></i>
                                    </el-input>
                                    <span v-else>{{formData.settlementUnitName}}</span>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="结算日期"
                                prop="settlementDate"
                            >
                                <el-date-picker
                                    v-model="formData.settlementDate"
                                    type="date"
                                    placeholder="请选择结算日期"
                                    value-format="yyyy-MM-dd"
                                    v-if='!isRedSingle'
                                ></el-date-picker>
                                <span v-else>{{formData.settlementDate}}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="预付款金额(元)" prop="amount">
                                <el-input
                                    type="number"
                                    v-enter-float="{
                                        set: formData,
                                        key: 'amount'
                                    }"
                                    v-model="formData.amount"
                                    :max="maxAmount"
                                    v-if='!isRedSingle'
                                ></el-input>
                                <span v-else>{{formData.amount}}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="币种" prop="currencyId">
                                {{ formData.currency }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item
                                label="累计预付款金额(元)"
                                prop="cumulativeAmount"
                            >
                                {{ formData.cumulativeAmount }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="冲预付款金额(元)"
                                prop="writeOffAmount"
                            >
                                {{ formData.writeOffAmount }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="本位币" prop="baseCurName">
                                {{ formData.baseCurName }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="传输财务共享" prop="easId">
                                {{ !formData.easId ? '未上传' : '已上传' }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="状态" prop="state">
                                {{ getState(formData.state) }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" v-if="isRedSingle">
                            <el-form-item label="冲红单">
                                <span :style="redBillStateStyle">{{
                                    redBillStateFun
                                }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="备注">
                                <el-input
                                    type="textarea"
                                    :rows="2"
                                    resize="none"
                                    placeholder="请输入内容"
                                    v-model="formData.remarks"
                                    maxlength='500'
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </div>
        <div class="buttons">
            <el-button
                type="primary"
                style="background: #2e61d7"
                @click="onSave"
                >保存</el-button
            >
            <el-button @click="handleClose">取消</el-button>
        </div>
    </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import request from '@/api/materialSettlement/supplierPayment'
import { formatDate, selectDataClient, openAppClient } from '@/utils/common'
import { mapMutations, mapState } from 'vuex'

let oldRouter = {} // 上一个页面来源
export default {
    data () {
        return {
            billType: '1018',
            //表单数据
            formData: {
                amount: '',
                baseCurAmount: 0,
                baseCurId: '',
                baseCurName: '',
                baseCurRate: 0,
                billId: '',
                billNo: '',
                contractAmount: '',
                contractBillId: '',
                contractBillNo: '',
                contractName: '',
                contractTypeName: '',
                contractTypeValue: 0,
                cumulativeAmount: '',
                currency: '',
                currencyId: '',
                easId: '',
                evaluationLevel: '',
                founderId: '',
                founderName: '',
                gmtCreate: '',
                gmtModified: '',
                isRed: 0,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                previousTotalAmount: '',
                redBillId: '',
                redBillNo: '',
                redBillState: null,
                remarks: '',
                rmbAmount: 0,
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                settlementDate: formatDate(new Date(), 'yyyy-MM-dd'),
                settlementUnitId: '',
                settlementUnitName: '',
                sourceId: '',
                sourceNumber: '',
                state: 0,
                workId: '',
                writeOffAmount: ''
            },
            maxAmount: 0,
            orgId: '', //机构id
            orgName: '', //机构名称
            val: '', //冲预付款金额（元）：
            rules: {
                orgName: [{ required: true, message: '请带出单据机构', trigger: ['blur', 'change'] }],
                settlementDate: [{ required: true, message: '请选择结算日期', trigger: ['blur', 'change'] }],
                contractTypeName: [{ required: true, message: '请带出合同类型', trigger: ['blur', 'change'] }],
                contractName: [{ required: true, message: '请带出合同名称', trigger: ['blur', 'change'] }],
                settlementUnitName: [{ required: true, message: '请选择结算单位', trigger: ['blur', 'change'] }],
                amount: [{ required: true, message: '请填写预付款金额', trigger: ['blur', 'change'] }],
                cumulativeAmount: [{ required: true, message: '请计算累计预付款金额', trigger: ['blur', 'change'] }],
                baseCurName: [{ required: true, message: '请带出本位币', trigger: ['blur', 'change'] }],
            },
            isRedSingle: false,
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            }
        }
    },
    computed: {
        ...mapState(['userInfo']),
        ...mapState('contract', ['ctClassify']),
        ...mapState('equip', ['equipData']),
        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.formData.redBillState) {
            case 0:
                redState = '冲销中'
                break
            case 1:
                redState = '冲销中'
                break
            case 2:
                redState = '已冲销'
                break
            case 3:
                redState = '红单'
                break
            }
            return redState
        }
    },
    watch: {
        'formData.redBillState' () {
            if (this.formData.redBillState == 3) {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.formData.redBillState == 0 ||
                this.formData.redBillState == 1
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.formData.redBillState == 2) {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        },
        'formData.amount' (val) {

            const tatol = +this.formData.previousTotalAmount + +val
            // 累计预付款金额不能超合同中的预付款金额
            if (tatol > this.formData.contractAmount) {
                this.clientPop(
                    'err',
                    '累计预付款金额不能超合同中的预付款金额:' + this.formData.contractAmount
                )
                this.formData.amount = +(this.formData.contractAmount - this.formData.previousTotalAmount).toFixed(2)
            }
            //更新累计预付款金额
            this.formData.cumulativeAmount = +(+this.formData.previousTotalAmount + +this.formData.amount).toFixed(2)
            //更新本位币
            this.formData.baseCurAmount =
                (this.formData.baseCurRate * this.formData.amount * 1).toFixed(
                    2
                ) * 1
        }
    },
    beforeRouteEnter (to, from, next) {
        oldRouter = from
        next()
    },
    beforeRouteLeave (to, from, next) {
        oldRouter = null
        next()
    },
    mounted () {
        this.formData.orgId = this.userInfo.orgInfo.orgId
        this.formData.orgName = this.userInfo.orgInfo.orgName
        this.billId = this.$route.query.billid
        if (this.$route.query.isRedSingle === '1') {
            this.initRedData()
            this.isRedSingle = true
        } else {
            this.isRedSingle = false
        }
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        //获取红单初始化信息
        async initRedData () {
            const res = await request.initRed({ billId: this.billId })
            this.formData = res
        },

        //获取截止上期末累计预付款金额
        getPreviousTotalAmount (contractId) {
            request
                .getPreviousTotalAmount({ contractId })
                .then(res => {
                    if (res.code) {
                        this.formData.previousTotalAmount = +(res.data) || 0
                    } else {
                        this.formData.previousTotalAmount = +(res) || 0
                        this.formData.amount = +(this.formData.contractAmount - this.formData.previousTotalAmount).toFixed(2)
                    }

                })
        },
        //弹框选择结算单位
        onSelectHetong () {
            selectDataClient({
                SelectServiceToken:
                    '/subcontract/thirdParty/getSupplierSettlement', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: '', // 接口参数(name为模拟参数)
                Title: '选择机材合同' // 标题
            })
                .then(async val => {
                    // this.setSelectedInfo(val)
                    // openAppClient('/showSelectedData', '选择结果')
                    const item = val[0]
                    this.formData.baseCurId = item.baseCurId
                    this.formData.baseCurName = item.baseCurName
                    this.formData.baseCurRate = item.baseCurRate
                    this.formData.contractAmount = item.advanceCharge // 合同预付款金额,用于下次进入时,不能大于此金额
                    this.formData.amount = item.advanceCharge //默认等于合同预付款金额
                    this.maxAmount = item.advanceCharge
                    this.remainingAmount = item.advanceCharge
                    this.formData.contractBillId = item.contractId
                    this.formData.contractName = item.contractName
                    this.formData.contractBillNo = item.contractNumber
                    this.formData.contractTypeValue = item.contractType
                    const findObj = this.ctClassify.contractType.find(
                        typeItem => typeItem.value === item.contractType
                    )
                    if (findObj) {
                        this.formData.contractTypeName = findObj.label
                    }
                    this.formData.currencyId = item.currencyId
                    this.formData.currency = item.currencyName
                    this.formData.settlementUnitId = item.secondPartyId
                    this.formData.settlementUnitName = item.secondPartyName
                    await this.getPreviousTotalAmount(this.formData.contractBillId)

                })
                .catch(err => {
                    alert(err.message)
                })
        },
        //查看合同
        onViewContract () {
            //1物资采购、2周材租赁、3加工、4设备采购、5设备租赁、6服务采购
            let url = ''
            let title = ''
            switch (this.formData.contractTypeValue) {
            case 1:
                url = 'ctMaterialApplyShow'
                title = '物资采购合同'
                break
            case 2:
                url = 'ctRevolvMaterialApplyShow'
                title = '周材租赁合同'
                break
            case 3:
                url = 'processingContractApplyShow'
                title = '加工合同'
                break
            case 4:
                url = 'ctEquipmentPurchaseApplyShow'
                title = '设备采购合同'
                break
            case 5:
                url = 'ctEquipmentLeaseApplyShow'
                title = '设备租赁合同'
                break
            case 6:
                url = 'serviceProcurementApplyShow'
                title = '服务采购合同'
                break
            }
            openAppClient(
                `/${url}?billid=${this.formData.contractBillId}&isview=true`,
                `查看${title}`
            )
        },
        //保存按钮
        onSave () {
            this.$refs['ruleForm'].validate(valid => {
                if (valid) {
                    request.paymentAdd(this.formData).then(res => {
                        this.clientPop(
                            'info',
                            '保存成功，是否继续？',
                            () => {
                                this.$router.replace(
                                    `/supplierPaymentEdit?billid=${res}`
                                )
                            },
                            null,
                            () => {
                                this.$router.replace('/supplierPayment')
                            }
                        )
                    })
                }
            })
        },
        //取消按钮
        handleClose () {
            if (oldRouter.path === '/supplierPayment') {
                this.$router.back()
            } else {
                this.$router.replace('/supplierPayment')
            }
        },
        getState (state) {
            const findObj = this.equipData.state.find(
                item => item.value === Number(state)
            )
            return findObj ? findObj.label : ''
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}

.el-tab-pane {
    margin-left: -10px;
}
</style>
